<?php

namespace app\api\service;

use app\api\dao\UserDao;
use app\api\model\User;
use app\api\trait\LoginSession;
use think\exception\ValidateException;
use app\api\validate\UserValidate;

class UserService
{
    use LoginSession;



    public function __construct(protected UserDao $userDao = new UserDao())
    {

    }


    public function login($data): User
    {
        (new UserValidate())->goCheck($data);

        $user = $this->userDao->getByUsername($data['username']);
        if (!$user) {
            throw new ValidateException('该用户名不存在!');
        }

        if (!password_verify($data['password'], $user->password)) {
            throw new ValidateException('密码错误!');
        }
        $this->setLoginUser($user);
        //todo 登录记录

        return $user->hidden(['password']);

    }

    public function register($data): User
    {

        (new UserValidate())->goCheck($data);

        if ($this->userDao->existByUsername($data['username'])) {
            throw new ValidateException('该用户名已存在');
        }
        return $this->userDao->add($data['username'], $data['password']);
    }

}
